/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.twang.stock.common.http;

import com.alibaba.fastjson.JSONArray;
import com.jayway.jsonpath.JsonPath;
import com.twang.stock.Entity.ShiShiData;
import com.twang.stock.dto.TenXunStock;
import com.twang.stock.entity.zq.ZhaiQuanMinutes;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.assertj.core.util.Lists;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 *
 * @author ryu
 */
@Slf4j
public class HtmlTools {

    public static void main(String[] args) throws InterruptedException {
//        List<String> ids = Lists.newArrayList();
//        ids.add("sh688318");
//        List<String> dataList =  httpTenXun("sh688318");
//        String result = dataList.get(0);
//        List<String> strings = JSONObject.parseArray(result, String.class);

        //  List<TenXunStock> list= httpGet("sz000628");
        // httpTenXun("sz000628");
        //  HtmlTools.httpGet("sz000938");

        //  getGpdatas(Lists.newArrayList("sh110044"));

        String html = getKezhuanZhaiList("7").get(0);
        List<ZhaiQuanMinutes> zhaiQuanMinutesList = JSONArray.parseArray(html, ZhaiQuanMinutes.class);

    }

    public static List<String> getKezhuanZhaiList(String page) {
        String urlString = "";
        try {
            urlString = new StringBuffer("https://vip.stock.finance.sina.com.cn/quotes_service/api/json_v2.php/Market_Center.getHQNodeDataSimple?page=").append(page)
                    .append("&num=80&sort=symbol&asc=1&node=hskzz_z&_s_r_a=page").toString();
            List<String> html = new ArrayList<String>();
            URL url = new URL(urlString);

            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestProperty("Referer", "https://finance.sina.com.cn");
            try (InputStreamReader isr = new InputStreamReader(conn.getInputStream(), "GBK");
                 BufferedReader br = new BufferedReader(isr)) {
                String temp;
                while ((temp = br.readLine()) != null) {
                    html.add(temp);
                }
            }
            return html;
        } catch (IOException e) {
            log.error("url={}  error，Referer=https://finance.sina.com.cn  exception={}", urlString, e);
            return null;
        }
    }

    private static List<String> getHtml(String urlString) {
        try {
            List<String> html = new ArrayList<String>();
            URL url = new URL(urlString);

            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestProperty("Referer","https://finance.sina.com.cn");
            try (InputStreamReader isr = new InputStreamReader(conn.getInputStream(), "GBK");
                 BufferedReader br = new BufferedReader(isr)) {
                String temp;
                while ((temp = br.readLine()) != null) {
                    html.add(temp);
                }
            }
            return html;
        } catch (IOException e) {
                log.error("url={}  error，Referer=https://finance.sina.com.cn  exception={}",urlString,e);
            return null;
        }
    }
        /**
         * http://hq.sinajs.cn/list=s_sh000001
         */
    private static List<String> getHtmlDatas(List<String> ids) throws InterruptedException {
        int count = 0;
        List<String> gpdata = new ArrayList<>();
        StringBuilder gpids = new StringBuilder();

        for (String dt : ids) {
            gpids.append(dt);
            // System.out.println(dt);
            gpids.append(",");
        }
        gpdata = getHtml("http://hq.sinajs.cn/list=" + gpids.substring(0, gpids.length() - 1));

        return gpdata;
    }

    public static int[] getDate() {
        Calendar cal = Calendar.getInstance();// 取当前日期。
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH) + 1;
        int day = cal.get(Calendar.DAY_OF_MONTH);
        int hour = cal.get(Calendar.HOUR_OF_DAY);
        int minute = cal.get(Calendar.MINUTE);
        int second = cal.get(Calendar.SECOND);
        int[] dt = new int[2];
        dt[0] = (year * 10000 + month * 100 + day);
        dt[1] = hour * 10000 + minute * 100 + second;
        return dt;
    }

    public static List<ShiShiData> getGpdatas(List<String> ids) throws InterruptedException {
        Thread.sleep(100);
        List<ShiShiData> ShiShiData = new ArrayList<>();
        int[] gdt = getDate();
        List<String> outstr = getHtmlDatas(ids);

        for (String temp : outstr) {
            if (temp.length() < 30) {
                continue;
            }
            String[] strarray;
            ShiShiData dt = new ShiShiData();
            strarray = temp.split(",");
            dt.setGetdate(gdt[0]);
            dt.setGettime(gdt[1]);
            dt.setCode(strarray[0].split("_")[2].split("=")[0]);
            dt.setGpid(Integer.parseInt(strarray[0].trim().substring(13, 19)));
            dt.setGpname(strarray[0].trim().substring(strarray[0].trim().indexOf("=") + 2));
            dt.setOpenprice(Float.parseFloat(strarray[1].trim()));
            dt.setOldprice(Float.parseFloat(strarray[2].trim()));
            dt.setPrice(Float.parseFloat(strarray[3].trim()));
            dt.setMaxprice(Float.parseFloat(strarray[4].trim()));
            dt.setMinprice(Float.parseFloat(strarray[5].trim()));
            dt.setSumvol((int)(Long.parseLong(strarray[8].trim()) / 100.00));
            dt.setAmount(Float.parseFloat(strarray[9].trim()));
            if (dt.getPrice() < 0.1 || dt.getAmount() < 0.1 || dt.getSumvol() < 1) {
                continue;
            }
            dt.setAvgprice((float) (Double.parseDouble(strarray[9].trim()) / (Long.parseLong(strarray[8].trim()))));
            dt.setBv1(Long.parseLong(strarray[10].trim()));
            dt.setBp1(Float.parseFloat(strarray[11].trim()));
            dt.setBv2(Long.parseLong(strarray[12].trim()));
            dt.setBp2(Float.parseFloat(strarray[13].trim()));
            dt.setBv3(Long.parseLong(strarray[14].trim()));
            dt.setBp3(Float.parseFloat(strarray[15].trim()));
            dt.setBv4(Long.parseLong(strarray[16].trim()));
            dt.setBp4(Float.parseFloat(strarray[17].trim()));
            dt.setBv5(Long.parseLong(strarray[18].trim()));
            dt.setBp5(Float.parseFloat(strarray[19].trim()));
            //
            dt.setSv1(Long.parseLong(strarray[20].trim()));
            dt.setSp1(Float.parseFloat(strarray[21].trim()));
            dt.setSv2(Long.parseLong(strarray[22].trim()));
            dt.setSp2(Float.parseFloat(strarray[23].trim()));
            dt.setSv3(Long.parseLong(strarray[24].trim()));
            dt.setSp3(Float.parseFloat(strarray[25].trim()));
            dt.setSv4(Long.parseLong(strarray[26].trim()));
            dt.setSp4(Float.parseFloat(strarray[27].trim()));
            dt.setSv5(Long.parseLong(strarray[28].trim()));
            dt.setSp5(Float.parseFloat(strarray[29].trim()));
            String[] strtemp;
            strtemp = strarray[30].trim().split("-");
            dt.setGpdate(strtemp[0].trim()  +strtemp[1].trim() + strtemp[2].trim());
            strtemp = strarray[31].trim().split(":");
            dt.setGptime(strtemp[0].trim() + strtemp[1].trim());
            dt.setZhangdie((
                            new BigDecimal(dt.getPrice() - dt.getOldprice()).divide(new BigDecimal(dt.getOldprice()), 5, BigDecimal.ROUND_HALF_UP)
                    ).multiply(new BigDecimal(100)).setScale(2,BigDecimal.ROUND_HALF_UP));
//            if (dt.getGptime() < 91500) {
//                continue;
//            }
            ShiShiData.add(dt);
        }
        return ShiShiData;
    }

    /**
     * http://qt.gtimg.cn/q=sz002261
     * @param code
     * @return
     */

    public static List<TenXunStock> httpGet(String code) {
        try {
           String urlString="http://qt.gtimg.cn/q="+code;
            List<TenXunStock> html = new ArrayList<TenXunStock>();

            URL url = new URL(urlString);

            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestProperty("Referer","https://qt.gtimg.cn");

            try (InputStreamReader isr = new InputStreamReader(conn.getInputStream(), "GBK");
                 BufferedReader br = new BufferedReader(isr)) {
                String temp;

                while ((temp = br.readLine()) != null) {
                    TenXunStock tenXunStock=cvoertDTO(temp);
                    html.add(tenXunStock);
                }
            }
            return html;
        } catch (IOException e) {
            log.error("url={}  error，腾讯数据  exception={}",code,e);
            return null;
        }
    }

    public static TenXunStock cvoertDTO(String stockData){
        System.out.println(stockData);
        stockData = stockData.substring(stockData.indexOf("\"") + 1, stockData.length() - 1);

        // Split the string into an array of values
        String[] values = stockData.split("~");

        // Create a new Stock object
        TenXunStock stock = new TenXunStock();

        // Populate the Stock object with values from the string
        stock.setExchange(Integer.parseInt(values[0]));
        stock.setStockName(values[1]);
        stock.setStockCode(values[2]);
        stock.setCurrentPrice(StringUtils.isEmpty(values[3])?BigDecimal.ZERO:new BigDecimal(values[3]));
        stock.setPriceChange(StringUtils.isEmpty(values[4])?BigDecimal.ZERO:new BigDecimal(values[4]));
        if(values.length>32){
            stock.setPriceChangePercentage(StringUtils.isEmpty(values[32])?BigDecimal.ZERO:new BigDecimal(values[32]));
        }
        stock.setTradingVolume(StringUtils.isEmpty(values[6])?BigDecimal.ZERO:new BigDecimal(values[6]));
        stock.setTurnover(StringUtils.isEmpty(values[7])?BigDecimal.ZERO:new BigDecimal(values[7]));

        if(null==stock.getPriceChangePercentage()){
            stock.setPriceChangePercentage(StringUtils.isEmpty(values[4])?BigDecimal.ZERO:new BigDecimal(values[4]));
        }
        return stock;
    }


    /**
     * http://qt.gtimg.cn/q=sz002261
     * @param code
     * @return
     */

    public static List<String> httpTenXun(String code) {
        try {
            String urlString=new StringBuilder("https://web.ifzq.gtimg.cn/appstock/app/minute/query?code=").append(code).toString();
            List<String> html = Lists.newArrayList();
            URL url = new URL(urlString);

            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestProperty("" +
                    "" +
                    "","https://qt.gtimg.cn");

            try (InputStreamReader isr = new InputStreamReader(conn.getInputStream(), "GBK");
                 BufferedReader br = new BufferedReader(isr)) {
                String temp;
                while ((temp = br.readLine()) != null) {
                   // FundTrendResponseData fundTrendResponseData = JSONObject.parseObject(temp,FundTrendResponseData.class);
                    String lamX=new StringBuffer("$.data.").append(code).append(".").append("data").append(".").append("data").toString();
                    String data = JsonPath.read(temp, lamX).toString();
                    html.add(data);
                }
            }
            return html;
        } catch (IOException e) {
            log.error("url={}  error，腾讯数据  exception={}",code,e);
            return null;
        }
    }


}
